package io.jnet.server.serverchannelcontext;

import java.nio.channels.AsynchronousSocketChannel;
import com.jfireframework.baseutil.collection.buffer.ByteBuf;
import io.jnet.common.api.impl.BaseChannelContext;
import io.jnet.common.bufstorage.BufStorage;
import io.jnet.common.bufstorage.BufStorage.StorageType;
import io.jnet.common.decodec.FrameDecodec;
import io.jnet.common.streamprocessor.ProcesserUtil;
import io.jnet.common.streamprocessor.StreamProcessor;
import io.jnet.common.util.AioListener;

public abstract class AbstractServerChannelContext extends BaseChannelContext
{
    private final boolean supportPush;
    
    public AbstractServerChannelContext(BufStorage bufStorage, int maxMerge, AioListener serverListener, StreamProcessor[] processors, AsynchronousSocketChannel socketChannel, FrameDecodec frameDecodec)
    {
        super(bufStorage, maxMerge, serverListener, processors, socketChannel, frameDecodec);
        supportPush = bufStorage.type() == StorageType.mpsc;
    }
    
    @Override
    public void push(Object send, int index) throws Throwable
    {
        if (supportPush == false)
        {
            throw new UnsupportedOperationException("只有SPSC类型的BufStorage才支持推送功能");
        }
        Object finalResult = ProcesserUtil.process(this, processors, send, index);
        if (finalResult instanceof ByteBuf<?>)
        {
            bufStorage.putBuf((ByteBuf<?>) finalResult);
            writeHandler.registerWrite();
        }
    }
}
